<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ page import="com.twoscreen.Event"%>
<%@ page import="com.twoscreen.PMF"%>
<%@ page import="com.twoscreen.TUser"%>
<%@ page import="com.twoscreen.Points"%>
<%@ page import="com.twoscreen.Video"%>
<%@ page import="javax.jdo.PersistenceManager" %>
<%@ page import="javax.jdo.Query" %>
<%@ page import="java.util.List" %>
<%@ page import="java.util.Date" %>
<%@ page import="java.util.Map" %>
<%@ page import="java.util.logging.Logger" %>
<%@ page import="com.google.appengine.api.users.User" %>
<%@ page import="com.google.appengine.api.users.UserService" %>
<%@ page import="com.google.appengine.api.users.UserServiceFactory" %>
<% 

	Logger log = Logger.getLogger("text");
	
	//Variables
	Cookie[] cookies = request.getCookies();
	TUser tuser = null;
	Boolean producer = false;
	String viewerId = null;
	String username = null;
	String points = null;
	String producerAccessToken = null;
	String videoId = request.getParameter("videoId");
	String videoTitle = request.getParameter("videoTitle");
	String videoImg = request.getParameter("videoImg");
	UserService userService = UserServiceFactory.getUserService();
	User user = userService.getCurrentUser();
	Boolean enabledVideo = false;
	
	//Check if there is a policy cookie and get it
	Boolean showCookieNotice = true;
	if (cookies != null) {
		for (int i=0 ; i<cookies.length ; i++) {
			if (cookies[i].getName().equals("cookie-dismiss")) {
				showCookieNotice = false;
			}
		}
	}
	
	//If the user is logged in
	if (user != null) {
		//Set user variables
		tuser = TUser.getTUser(user);
		username = tuser.getUserName();
		points = Points.getPointsTotal(tuser);
		viewerId = tuser.getViewerId();
		String producerRefreshToken = tuser.getProducerRefreshToken(); //never in cookie
		//Get from the cookie
		if (cookies != null) {
			Boolean set = false;
			for ( int i=0 ; i<cookies.length ; i++) {
				log.info("in the cookie loop");
				if (cookies[i].getName().equals("access")) {
					producerAccessToken = cookies[i].getValue();
					log.info("setting access token to cookie: " + cookies[i].getValue());
					set = true;
				}
			}
			log.info("done cookie loop set: ");
			if (set == false) {
				//nothing in cookie - try from data store
				log.info("nothing in cookie getting access from data store");
				producerAccessToken = tuser.getProducerAccessToken();
			}
		} else {
			//nothing in cookie - try from data store
			log.info("nothing in cookie getting access from data store");
			producerAccessToken = tuser.getProducerAccessToken();
		}
		Date producerAccessTokenExpiry = null;
		//if the expiry in the data store is null try the cookie
		if (cookies != null) {
			Boolean set = false;
			for ( int i=0 ; i<cookies.length ; i++) {
				log.info("in the cookie loop");
				if (cookies[i].getName().equals("expiry")) {
					producerAccessTokenExpiry = new Date(Long.parseLong(cookies[i].getValue()));
					log.info("setting expiry token to cookie: " + cookies[i].getValue());
					set = true;
				}
			}
			log.info("done cookie loop");
			if (set == false) {
				//nothing in cookie - try from data store
				log.info("nothing in cookie getting expiry from data store");
				producerAccessTokenExpiry = tuser.getProducerAccessExpiry();
			}
		} else {
			//nothing in cookie - try from data store
			log.info("nothing in cookie getting expiry from data store");
			producerAccessTokenExpiry = tuser.getProducerAccessExpiry();
		}
		Date now = new Date();
		
		//Valid YT token?
		try {
			if (producerAccessTokenExpiry.before(new Date())) {
				//The token has expired - delete it
				log.info("date now: " + new Date() + " expiry: " + producerAccessTokenExpiry.getTime());
				log.info("date expired - removing token and expiry");
				producerAccessToken = null;
				producerAccessTokenExpiry = null;
			}
		} catch (Exception e) {
			log.info("caught exception on access token " + e);
		}
		if (producerAccessToken == null && producerRefreshToken != null) {
			//If invalid token with refresh token
			log.info("no token - refreshing");
			producerAccessToken = TUser.refreshAccessToken(user);
		}
		if (producerAccessToken != null) {
			//If valid
			producer = true;
		} else {
			//Show user auth page
		}
		log.info("set access token: " + producerAccessToken);
	} else {
		//remove the access and expiry cookies
		log.info("remove cookies");
		Cookie ac = new Cookie("access", null);
		ac.setMaxAge(0);
		ac.setPath("/");
		response.setContentType("text/html");
		response.addCookie(ac);
		Cookie ex = new Cookie("expiry", null);
		ex.setMaxAge(0);
		ex.setPath("/");
		response.setContentType("text/html");
		response.addCookie(ex);
	}
	
	String thisURL = request.getRequestURL().toString();
%>

<!doctype html>
<html>
	<head>
		<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
		<title>Two-screen | Create a video</title>
		<link href='https://fonts.googleapis.com/css?family=Montserrat|Exo:200,400' rel='stylesheet' type='text/css' />
		<link href="/css/web.css" rel="stylesheet" type="text/css" />
		<link href="/css/ui-lightness/jquery-ui-1.9.1.custom.min.css" rel="stylesheet" type="text/css" />
		<link rel="stylesheet" type="text/css" href="/css/jquery.fancybox.css?v=2.1.2" media="screen" />
		<script type="text/javascript" src="/js/cufon-yui.js"></script>
		<script type="text/javascript" src="/js/College_700.font.js"></script>
		<script type="text/javascript" src="/js/jquery-1.8.2.min.js"></script>
		<script type="text/javascript" src="/js/jquery.fancybox.js?v=2.1.3"></script>
		<script type="text/javascript" src="/js/jquery-ui-1.9.1.custom.min.js"></script>
		<script type="text/javascript" src="/js/userUpdateWeb.js"></script>
		<script type="text/javascript" src="/js/cookie.js"></script>
		<script type="text/javascript">
			Cufon.replace('h1#logo');
		</script>
		<script type="text/javascript">
			var viewerId = "<%= viewerId %>";
		</script>
		<script type="text/javascript">
			var _gaq = _gaq || [];
			_gaq.push(['_setAccount', 'UA-35281811-1']);
			_gaq.push(['_trackPageview']);
			
			(function() {
			  var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
			  ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
			  var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
			})();
		</script>
		
<% 
log.info("producer: "+ producer);
	if (videoId != null && producer) {
		//The user is a producer and creating content for a video
		try {
			enabledVideo = Video.getVideo(videoId).getEnabled();
		} catch (Exception e) {
			enabledVideo = true;
		}
%>
	
		<script type="text/javascript" src="/js/eventForm.js"></script>
		<script type="text/javascript" src="/js/eventBuilder.js"></script>
		<script type="text/javascript" src="/js/eventPlayer.js"></script>
		<script type="text/javascript">
			var videoId = "<%= videoId %>";
			var videoTitle = "<%= videoTitle %>";
			var videoImg = "<%= videoImg %>";
		</script>
		<script type="text/javascript" src="https://apis.google.com/js/plusone.js">
			{lang: 'en-GB',
			parsetags: 'explicit'}
		</script>

<% 
	} else if (producer) {
		//The user is a producer and looking for a video to create content for
%>
		<script type="text/javascript">
			var ytc = "<%= producerAccessToken %>";
		</script>
		<script type="text/javascript" src="/js/ytdata.js"></script>

<% 
	}
	//Start of page header
%>
	</head>
	<body>
	
	
		<div id="head-bg">
			<div class="inner-wrapper">
				<div id="header">
					<div id="head-logo">
						<a href="/"><img id="logo" alt="home" src="/images/logo2.png" /></a>
						<h1 id="logo"><a href="/">Two-screen</a></h1>
					</div>
					<ul class="menu">
<% 
	if (user != null) {
%>
						<li id="head-user">
							<h3 class="menu">you</h3>
							<ul class="head-sub">
								<li class="noHover"><h3>points: <%= points %></h3></li>
								<li><h3><a class="fancybox" href="#username-update-dialog">update username</a></h3></li>
								<li><h3>
										<a class="head-link" href="<%= userService.createLogoutURL(thisURL) %>">log out</a>
									</h3>
								</li>
							</ul>
						</li>
					

<% 
	} else {
%>
				
						<li id="head-user">
							<h3 class="menu"><a class="head-link" href="<%= userService.createLoginURL(thisURL) %>">log in</a></h3>
						</li>
				
<% 
	}
%>				
				
					
						<li id="head-explore">
							<h3 class="menu"><a class="head-link" href="/connect.jsp">watch</a></h3>
						</li>
						
						
						<li id="head-create">
							<h3 class="menu"><a class="head-link" href="/producers/index.jsp">create</a></h3>
						</li>
					</ul>
					
				</div>
				<div class="clear"></div>
			</div>
		</div>
	
	
<% 
	//End of page header
	
	//Start of page body
		
	if (producer) {

		//If the videoId is not passed show the user's video feed
		if (videoId == null) {
%>

		<div id="create-videofeed-bg">
			<div class="inner-wrapper">

<% 
	if (showCookieNotice) {
%>
				<%@ include file="/include/cookie-notice.html" %>
<% 
	}
%>			

				<h1>Choose a video to create interactive content:</h1>
				<div id="video-wall">
					<p>Loading video wall...</p>
				</div>
				<div class="clear"></div>
				<form id='select-video' name="select-video" action='/producers/index.jsp' method="post">
					<input id="form-video-id" type="hidden" value="" name="videoId">
					<input id="form-video-title" type="hidden" value="" name="videoTitle">
					<input id="form-video-img" type="hidden" value="" name="videoImg">
				</form>
			</div>
		</div>

<%
		//If the videoId is passed the user has selected a video to create events for - show the event creation
		} else {
%>

		<div id="create-video-bg" 
				<%if (enabledVideo==false) {%>style="background-image: url('/images/pink-stripe.png');"<%} %>>
			<div class="inner-wrapper">
				<h2>Instructions:</h2>
				<p>1. Press play on the video</p>
				<p>2. Skip forward to the time position you want to create an interactive event</p>
				<p>3. Press pause</p>
				<h2 id="video-disabled-text" style="color: red;
					<%if (enabledVideo==false) {%> display: inline;<%} %>">Video disabled</h2>
				<div id="videoDiv"></div>
				<div id="event-controls">
					<a id="event-scroll-position"></a>
					<div id="device-image">
						<div id="device-screen">
							<div id="app-screen-header">
								<div id="app-screen-logout-button"><span id="app-screen-logout-button-span"><span id="app-screen-logout-button-text">Log out</span></span></div>
								<h1 id="app-title-text">Click to add</h1>
							</div><!-- /header -->
							<div id="app-screen-content">
							</div><!-- /content -->
						</div>
					</div>
					<div id="app-homescreen" class="app-creation">
						<h3>4. Home screen</h3>
						<br>
						<a>The home screen is what's displayed to your viewer when the video is selected, before the first event is triggered</a>
						<br><br>
						<a>It displays your show's logo and title.</a>
						<br><br>
						<a>Click the logo and title in the app preview to the left to customise the appearance, then click save below.</a>
						<br><br>
						<button type="button" onclick="eventAjaxSubmit(false)">Save</button><button type="button" onclick="eventAjaxSubmit(true)">Later</button>
					</div>
					<div id="app-elements" class="app-creation">
						<h3>4. Drag an element to begin</h3>
						<br>
						<div id="multi-choice-2">Multiple choice question - 2 options</div>
						<div id="multi-choice-3">Multiple choice question - 3 options</div>
						<div id="multi-choice-4">Multiple choice question - 4 options</div>
						<div id="heading3">Heading text</div>
						<div id="text">Body text</div>
						<div id="image">Image</div>
						<div id="tube-status">London Tube status</div>
						<div id="google-plus">Google plus circles</div>
						<div id="facebook-like">Facebook like</div>
						<div id="twitter-tweet">Twitter tweet with hashtag</div>
						<button type="button" onclick="eventAjaxSubmit()">Save</button>
					</div>
					<div id="current-events">

<%
	if (enabledVideo) {
%>
						
						<button type="button" id="video-enable" onclick="changeVideoStatus(true);" style="display:none;">
							Enable Video</button>
						<button type="button" id="video-disable" onclick="changeVideoStatus(false);">Disable Video</button>

<%
	} else {
%>

						<button type="button" id="video-enable" onclick="changeVideoStatus(true);">Enable Video</button>
						<button type="button" id="video-disable" onclick="changeVideoStatus(false);" style="display:none;">
							Disable Video</button>

<%
	}
%>
						
						<h3>Current events</h3>
						<br>
						<table id="current-events-table">
							<thead>
								<tr>
									<th>Title</th>
									<th>Time</th>
									<th>Delete</th>
								</tr>
							</thead>
							<tbody>
							</tbody>
						</table>
					</div>
					<div class="clear"></div>
				</div>
			</div>
		</div>
		
		
		<!-- Dialog form -->
		<div id="dialog-single-input" title=".">
		    <p class="validateTips">All form fields are required.</p>
		    <form>
		    <fieldset>
		        <label for="single-input-text" id="dialog-single-input-label"></label>
		        <textarea rows="1" cols="30" style="resize:none;" name="single-input-text" id="dialog-single-input-text" class="text ui-widget-content ui-corner-all"></textarea>
		    </fieldset>
		    </form>
		</div>

<%
		}
	} else if (tuser == null) {
		//The user is not signed in
%>

		<div id="create-benefits-bg">
			<div class="inner-wrapper">


<% 
	if (showCookieNotice) {
%>
				<%@ include file="/include/cookie-notice.html" %>
<% 
	}
%>	

				<h1>Want to create two-screen content?</h1>
				<h3 class="thin">Creating content is effortless, you just need to 
					<a href="<%= userService.createLoginURL(thisURL) %>">log in</a>.</h3>
				<div class="feature-box first blue">
					<h3>Questions</h3>
					<p>Adding appropriate and well designed questions to your video allows you to
						collect opinions and ratings from your audience. These can be used to generate
						visualisations of audience behaviour for use on your website.</p>
				</div>
				<div class="feature-box green">
					<h3>Social media</h3>
					<p>You can link your social media presence to your video allowing you and your
						audience to easily connect and engage. You can use this connection to influence
						future shows or offer rewards to your audience.</p>
				</div>
				<div class="feature-box grey">
					<h3>YouTube based</h3>
					<p>You can get started straight away creating two-screen content for your
						YouTube uploaded videos, the two-screen content you create is instantly 
						available on this site for your audience to interact with and enjoy.</p>
				</div>
				
				<div class="clear"></div>
				<div class="space"></div>
				
			</div>
		</div>

<%
	} else if (tuser != null) {
		//The user is signed in but does not have producer access
%>

		<div id="create-benefits-bg">
			<div class="inner-wrapper">
			
<% 
	if (showCookieNotice) {
%>
				<%@ include file="/include/cookie-notice.html" %>
<% 
	}
%>

				<h1>Nearly there!</h1>
				<h3 class="thin">It looks like this is your first time, don't worry we're here to help.</h3>
				<p>We need to link your account with YouTube so we know which videos are yours.</p>
				<p>Don't worry we wont alter any of your data on YouTube. The only information we store 
					from YouTube is your video's title, ID, and thumbnail image so we can add it to our 
					video wall.</p>
				<p>The next page will take you to the YouTube authorisation page, once you authorise
					us to access your video data you can get started creating two-screen content!</p>
				<h3 class="thin">If you are happy for us to store this information please 
					<a href="/authorise?viewer=<%= viewerId %>">click here.</a></h3>
			</div>
		</div>

<%
	}
%>
		
		<%@ include file="/include/footer.html" %>
		
		<div id="username-update-dialog" style="width:400px;display: none;">
			<h3>Update user name: <span id="currentUn"><%= username %></span></h3>
			<br>
			<label for="username">User name:</label><input type="text" name="username" id="username-input">
			<br>
			<p id="unError"></p>
			<div id="unSuggestions"></div>
			<button type="button" onclick="userSave()">Save</button>
		</div>
		<div id="username-success" style="width:400px;display: none;">
			<h3 class="success">User name saved</h3>
		</div>
		
	</body>
</html>